package com.kx.smartdevice.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kx.smartdevice.cache.AreaCache;
import com.kx.smartdevice.constants.ResultCode;
import com.kx.smartdevice.event.AreaChangeEvent;
import com.kx.smartdevice.exceptions.DeleteErrorException;
import com.kx.smartdevice.exceptions.QueryErrorException;
import com.kx.smartdevice.exceptions.UpdateErrorException;
import com.kx.smartdevice.mapper.AreaMapper;
import com.kx.smartdevice.pojo.Area;
import com.kx.smartdevice.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @ClassName AreaServiceImpl
 * @Author Sun
 * @Date 2021/5/29 16:08
 */
@Service
@Transactional
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaCache areaCache;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    ApplicationContext context;//用来发布事件

    @Override
    public PageInfo<Area> findAllAreaByPage(int pageNum, int pageSize, String areaname, int status) {
        //存储符合查询条件的数据
        ArrayList<Area> areas = new ArrayList<>();
        PageHelper.startPage(pageNum, pageSize);
        //先从缓存中找
        Set<Area> allData = areaCache.getAllData();
        if (allData == null) {//缓存中没有数据，查询数据库，但是这种情况根本不存在，因为缓存中存储的是数据库中的所有数据
            Set<Area> allAreaByPage = areaMapper.findAllAreaByPage(areaname, status);
            areas.addAll(allAreaByPage);
            PageInfo<Area> pageInfo = new PageInfo<>(areas);
            return pageInfo;
        }
        //但是还要根据名字和状态在缓存红进行搜索数据，所以接下来要进一步的判断数据
        if ("".equalsIgnoreCase(areaname) && status == -100) {//搜索框不输入内容，默认查询所有
            areas.addAll(allData);
        } else {
            for (Area area : allData) {
                if (Pattern.matches("^(.*" + areaname + ".*)$", area.getAreaname()) && area.getStatus().equals(status)) {
                    areas.add(area);
                } else if (Pattern.matches("^(.*" + areaname + ".*)$", area.getAreaname()) && status == -100) {
                    areas.add(area);
                } else if ("".equals(areaname) && area.getStatus().equals(status)) {
                    areas.add(area);
                }
            }
        }

        PageInfo<Area> pageInfo = new PageInfo<>(areas);

        return pageInfo;

    }


    @Override
    public void addAreas(Area area) {
        if (area == null || area.isEmpty()) {
            throw new UpdateErrorException("传传递的数据为空,请检查", ResultCode.NULL_DATA);
        }
        areaMapper.addAreas(area);

        //更新缓存数据
        context.publishEvent(new AreaChangeEvent());
    }

    @Override
    public int updateArea(Area area) {
        if (area == null) {
            throw new DeleteErrorException("没有传递数据", ResultCode.NULL_DATA);
        }
        int result  = areaMapper.updateArea(area);
        //更新缓存数据
        context.publishEvent(new AreaChangeEvent());
        return result;
    }


    @Override
    public int deleteAreaByIds(String[] ids) {
        if (ids.length==0) {
            throw new DeleteErrorException("用户id没有传递", ResultCode.DATA_NOT_ALLOWED);
        }
        int result = areaMapper.deleteAreaByIds(ids);

        //更新缓存数据
        context.publishEvent(new AreaChangeEvent());
        return result;
    }

    @Override
    public Area getAreaById(Long id) {
        if (id == null || id == 0) {
            throw new QueryErrorException("没有传递 id", ResultCode.NULL_DATA);
        }

        try {
            Area area = areaMapper.getAreaById(id);
            if (area == null) {
                throw new QueryErrorException("没有查询到结果", ResultCode.ERROR);
            }
            return area;
        } catch (Exception e) {
            e.printStackTrace();
            throw new QueryErrorException("查询失败", ResultCode.ERROR);
        }
    }

    @Override
    public List<Area> getAreaByParentId(Long id) {
        if (id == null || id == 0) {
            throw new QueryErrorException("没有传递 id", ResultCode.NULL_DATA);
        }

        try {
            List<Area> areaList = areaMapper.getAreaByParentId(id);
            return areaList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new QueryErrorException("查询失败", ResultCode.ERROR);

        }
    }

    @Override
    public List<Area> getAllFirstParentAreas(int status) {
        try {
            return areaMapper.getAllFirstParentAreas(status);
        } catch (Exception e) {
            e.printStackTrace();
            throw new QueryErrorException("查询异常", ResultCode.ERROR);
        }
    }

}
